import uuid
from datetime import datetime, date, time, timedelta
from decimal import Decimal

from django.test import TestCase
from django.utils import timezone
from django.core.exceptions import ValidationError
from django.db import transaction

from app.models import (
    User, MerchantInfo, Employee, Attendance, EmployeeActivity,
    LeaveRequest, PerformanceRecord, SalaryRecord, OrderItem, Order, Dish, Category
)
from app.services.employee_services import (
    EmployeeService, AttendanceService, EmployeeActivityService,
    LeaveRequestService, PerformanceService, SalaryService
)


class BaseEmployeeTestCase(TestCase):
    """员工服务测试基类"""

    def setUp(self):
        """设置测试数据"""
        # 创建测试用户 - 商家
        self.merchant_user = User.objects.create(
            id=uuid.uuid4(),
            username="test_merchant",
            phone="13800000001",
            password_hash="hashed_password",
            role="merchant"
        )

        # 创建商家信息
        self.merchant_info = MerchantInfo.objects.create(
            merchant_id=self.merchant_user.id,
            shop_name="测试餐厅",
            location="测试地址123号",
            contact_info="13800000001",
            introduction="这是一家测试餐厅",
            business_hours="9:00-22:00"
        )

        # 创建测试用户 - 员工
        self.employee_user = User.objects.create(
            id=uuid.uuid4(),
            username="test_employee",
            phone="13800000002",
            password_hash="hashed_password",
            role="customer"
        )

        # 创建另一个员工用户
        self.employee_user2 = User.objects.create(
            id=uuid.uuid4(),
            username="test_employee2",
            phone="13800000003",
            password_hash="hashed_password",
            role="customer"
        )

        # 创建分类和菜品（用于订单测试）
        self.category = Category.objects.create(
            category_id=uuid.uuid4(),
            merchant=self.merchant_info,
            category_name="测试分类"
        )

        self.dish = Dish.objects.create(
            dish_id=uuid.uuid4(),
            merchant=self.merchant_info,
            category=self.category,
            dish_name="测试菜品",
            price=Decimal('25.00'),
            stock=10
        )


class EmployeeServiceTest(BaseEmployeeTestCase):
    """员工服务测试"""

    def test_create_employee_success(self):
        """测试成功创建员工"""
        response = EmployeeService.create_employee(
            user_id=self.employee_user.id,
            merchant_id=self.merchant_info.merchant_id,
            real_name="张三",
            hire_date=date(2024, 1, 15),
            work_start_time=time(9, 0),
            work_end_time=time(18, 0),
            base_daily_salary=Decimal('200.00'),
            work_schedule={
                'monday': True, 'tuesday': True, 'wednesday': True,
                'thursday': True, 'friday': True, 'saturday': False, 'sunday': False
            },
            late_penalty_per_minute=Decimal('1.0'),
            early_leave_penalty_per_minute=Decimal('1.0'),
            activity_bonus_per_count=Decimal('5.0')
        )

        self.assertEqual(response.status_code, 201)
        self.assertEqual(response.data['code'], 201)
        self.assertEqual(response.data['message'], "员工创建成功")
        self.assertEqual(response.data['data']['user_id'], str(self.employee_user.id))

        # 验证数据库中的员工记录
        employee = Employee.objects.get(user_id=self.employee_user.id)
        self.assertEqual(employee.real_name, "张三")
        self.assertEqual(employee.base_daily_salary, Decimal('200.00'))
        self.assertTrue(employee.monday_work)
        self.assertFalse(employee.saturday_work)

    def test_create_employee_user_not_exist(self):
        """测试创建员工时用户不存在"""
        fake_user_id = uuid.uuid4()

        with self.assertRaises(ValidationError) as context:
            EmployeeService.create_employee(
                user_id=fake_user_id,
                merchant_id=self.merchant_info.merchant_id,
                real_name="张三",
                hire_date=date(2024, 1, 15),
                work_start_time=time(9, 0),
                work_end_time=time(18, 0),
                base_daily_salary=Decimal('200.00')
            )

        self.assertIn("用户不存在", str(context.exception))

    def test_create_employee_already_exists(self):
        """测试用户已是员工的情况"""
        # 先创建一个员工
        Employee.objects.create(
            user=self.employee_user,
            merchant=self.merchant_info,
            real_name="张三",
            hire_date=date(2024, 1, 15),
            work_start_time=time(9, 0),
            work_end_time=time(18, 0),
            base_daily_salary=Decimal('200.00')
        )

        # 再次尝试创建
        with self.assertRaises(ValidationError) as context:
            EmployeeService.create_employee(
                user_id=self.employee_user.id,
                merchant_id=self.merchant_info.merchant_id,
                real_name="李四",
                hire_date=date(2024, 1, 15),
                work_start_time=time(9, 0),
                work_end_time=time(18, 0),
                base_daily_salary=Decimal('200.00')
            )

        self.assertIn("该用户已是员工", str(context.exception))

    def test_update_employee_info_success(self):
        """测试成功更新员工信息"""
        # 先创建员工
        employee = Employee.objects.create(
            user=self.employee_user,
            merchant=self.merchant_info,
            real_name="张三",
            hire_date=date(2024, 1, 15),
            work_start_time=time(9, 0),
            work_end_time=time(18, 0),
            base_daily_salary=Decimal('200.00')
        )

        # 更新员工信息
        response = EmployeeService.update_employee_info(
            user_id=self.employee_user.id,
            real_name="张三丰",
            base_daily_salary=Decimal('250.00'),
            saturday_work=True
        )

        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.data['code'], 200)

        # 验证更新结果
        employee.refresh_from_db()
        self.assertEqual(employee.real_name, "张三丰")
        self.assertEqual(employee.base_daily_salary, Decimal('250.00'))
        self.assertTrue(employee.saturday_work)

    def test_get_employee_list_success(self):
        """测试获取员工列表"""
        # 创建两个员工
        Employee.objects.create(
            user=self.employee_user,
            merchant=self.merchant_info,
            real_name="张三",
            hire_date=date(2024, 1, 15),
            work_start_time=time(9, 0),
            work_end_time=time(18, 0),
            base_daily_salary=Decimal('200.00')
        )

        Employee.objects.create(
            user=self.employee_user2,
            merchant=self.merchant_info,
            real_name="李四",
            hire_date=date(2024, 1, 20),
            work_start_time=time(9, 0),
            work_end_time=time(18, 0),
            base_daily_salary=Decimal('220.00')
        )

        response = EmployeeService.get_employee_list(
            merchant_id=self.merchant_info.merchant_id
        )

        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.data['code'], 200)
        self.assertEqual(len(response.data['data']), 2)

        # 验证数据内容
        employee_names = [emp['real_name'] for emp in response.data['data']]
        self.assertIn("张三", employee_names)
        self.assertIn("李四", employee_names)


class AttendanceServiceTest(BaseEmployeeTestCase):
    """考勤服务测试"""

    def setUp(self):
        super().setUp()
        # 创建员工
        self.employee = Employee.objects.create(
            user=self.employee_user,
            merchant=self.merchant_info,
            real_name="张三",
            hire_date=date(2024, 1, 15),
            work_start_time=time(9, 0),
            work_end_time=time(18, 0),
            base_daily_salary=Decimal('200.00'),
            monday_work=True,
            tuesday_work=True,
            wednesday_work=True,
            thursday_work=True,
            friday_work=True,
            saturday_work=False,
            sunday_work=False
        )

    def test_clock_in_success(self):
        """测试成功上班打卡"""
        # 模拟周一上班打卡
        with self.settings(USE_TZ=False):
            # 设置为周一
            test_time = time(9, 15)  # 9:15 上班（迟到15分钟）

            response = AttendanceService.clock_in(
                user_id=self.employee_user.id,
                actual_time=test_time
            )

            self.assertEqual(response.status_code, 200)
            self.assertEqual(response.data['code'], 200)
            self.assertEqual(response.data['message'], "上班打卡成功")

            # 验证考勤记录
            attendance = Attendance.objects.get(
                employee=self.employee,
                work_date=timezone.now().date()
            )
            self.assertEqual(attendance.actual_start, test_time)
            self.assertIsNone(attendance.actual_end)

    def test_clock_in_already_clocked(self):
        """测试重复上班打卡"""
        # 先打卡一次
        AttendanceService.clock_in(user_id=self.employee_user.id)

        # 再次打卡
        with self.assertRaises(ValidationError) as context:
            AttendanceService.clock_in(user_id=self.employee_user.id)

        self.assertIn("今日已打卡上班", str(context.exception))

    def test_clock_out_success(self):
        """测试成功下班打卡"""
        # 先上班打卡
        AttendanceService.clock_in(user_id=self.employee_user.id)

        # 下班打卡
        test_time = time(18, 30)  # 18:30 下班（加班30分钟）
        response = AttendanceService.clock_out(
            user_id=self.employee_user.id,
            actual_time=test_time
        )

        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.data['code'], 200)
        self.assertEqual(response.data['message'], "下班打卡成功")

        # 验证考勤记录
        attendance = Attendance.objects.get(
            employee=self.employee,
            work_date=timezone.now().date()
        )
        self.assertEqual(attendance.actual_end, test_time)

    def test_clock_out_without_clock_in(self):
        """测试未上班就下班打卡"""
        with self.assertRaises(ValidationError) as context:
            AttendanceService.clock_out(user_id=self.employee_user.id)

        self.assertIn("今日尚未打卡上班", str(context.exception))

    def test_get_attendance_records(self):
        """测试获取考勤记录"""
        # 创建几天的考勤记录
        today = timezone.now().date()

        for i in range(3):
            work_date = today - timedelta(days=i)
            Attendance.objects.create(
                employee=self.employee,
                work_date=work_date,
                scheduled_start=time(9, 0),
                scheduled_end=time(18, 0),
                actual_start=time(9, 15),
                actual_end=time(18, 30)
            )

        response = AttendanceService.get_attendance_records(
            user_id=self.employee_user.id
        )

        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.data['code'], 200)
        self.assertEqual(len(response.data['data']), 3)


class EmployeeActivityServiceTest(BaseEmployeeTestCase):
    """员工活动服务测试"""

    def setUp(self):
        super().setUp()
        # 创建员工
        self.employee = Employee.objects.create(
            user=self.employee_user,
            merchant=self.merchant_info,
            real_name="张三",
            hire_date=date(2024, 1, 15),
            work_start_time=time(9, 0),
            work_end_time=time(18, 0),
            base_daily_salary=Decimal('200.00')
        )

        # 创建订单和订单项
        self.order = Order.objects.create(
            order_id=uuid.uuid4(),
            user=self.employee_user,  # 这里使用employee_user作为下单用户
            merchant=self.merchant_info,
            table_number="1",
            total_amount=Decimal('50.00'),
            status='in_preparation'
        )

        self.order_item = OrderItem.objects.create(
            order=self.order,
            dish=self.dish,
            quantity=2,
            unit_price=self.dish.price,
            status='in_preparation'
        )

    def test_record_activity_success(self):
        """测试成功记录员工活动"""
        response = EmployeeActivityService.record_activity(
            user_id=self.employee_user.id,
            order_id=self.order.order_id,
            dish_id=self.dish.dish_id,
            activity_type='cook_dish'
        )

        self.assertEqual(response.status_code, 201)
        self.assertEqual(response.data['code'], 201)
        self.assertEqual(response.data['message'], "活动记录成功")

        # 验证活动记录
        activity = EmployeeActivity.objects.get(
            employee=self.employee,
            order_item=self.order_item,
            activity_type='cook_dish'
        )
        self.assertIsNotNone(activity)

        # 验证订单项状态更新
        self.order_item.refresh_from_db()
        self.assertEqual(self.order_item.status, 'completed')

    def test_record_duplicate_activity(self):
        """测试重复记录活动"""
        # 先记录一次
        EmployeeActivityService.record_activity(
            user_id=self.employee_user.id,
            order_id=self.order.order_id,
            dish_id=self.dish.dish_id,
            activity_type='cook_dish'
        )

        # 再次记录相同活动
        with self.assertRaises(ValidationError) as context:
            EmployeeActivityService.record_activity(
                user_id=self.employee_user.id,
                order_id=self.order.order_id,
                dish_id=self.dish.dish_id,
                activity_type='cook_dish'
            )

        self.assertIn("该活动已记录", str(context.exception))

    def test_get_employee_activities(self):
        """测试获取员工活动记录"""
        # 创建活动记录
        EmployeeActivity.objects.create(
            employee=self.employee,
            order_item=self.order_item,
            activity_type='cook_dish',
            activity_time=timezone.now()
        )

        response = EmployeeActivityService.get_employee_activities(
            user_id=self.employee_user.id
        )

        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.data['code'], 200)
        self.assertEqual(len(response.data['data']), 1)

        activity_data = response.data['data'][0]
        self.assertEqual(activity_data['activity_type'], '做菜')
        self.assertEqual(activity_data['dish_name'], '测试菜品')


class LeaveRequestServiceTest(BaseEmployeeTestCase):
    """请假服务测试"""

    def setUp(self):
        super().setUp()
        # 创建员工
        self.employee = Employee.objects.create(
            user=self.employee_user,
            merchant=self.merchant_info,
            real_name="张三",
            hire_date=date(2024, 1, 15),
            work_start_time=time(9, 0),
            work_end_time=time(18, 0),
            base_daily_salary=Decimal('200.00')
        )

        # 创建审批员工（商家管理员）
        self.approver = Employee.objects.create(
            user=self.merchant_user,
            merchant=self.merchant_info,
            real_name="商家管理员",
            hire_date=date(2024, 1, 1),
            work_start_time=time(9, 0),
            work_end_time=time(18, 0),
            base_daily_salary=Decimal('300.00')
        )

    def test_submit_leave_request_success(self):
        """测试成功提交请假申请"""
        start_date = date.today() + timedelta(days=1)
        end_date = date.today() + timedelta(days=2)

        response = LeaveRequestService.submit_leave_request(
            user_id=self.employee_user.id,
            leave_type='sick',
            start_date=start_date,
            end_date=end_date,
            reason="身体不适，需要休息"
        )

        self.assertEqual(response.status_code, 201)
        self.assertEqual(response.data['code'], 201)
        self.assertEqual(response.data['message'], "请假申请提交成功")

        # 验证请假记录
        leave_request = LeaveRequest.objects.get(
            employee=self.employee,
            start_date=start_date,
            end_date=end_date
        )
        self.assertEqual(leave_request.status, 'pending')
        self.assertEqual(leave_request.reason, "身体不适，需要休息")

    def test_submit_leave_request_invalid_dates(self):
        """测试提交无效日期的请假申请"""
        start_date = date.today() + timedelta(days=2)
        end_date = date.today() + timedelta(days=1)  # 结束日期早于开始日期

        with self.assertRaises(ValidationError) as context:
            LeaveRequestService.submit_leave_request(
                user_id=self.employee_user.id,
                leave_type='sick',
                start_date=start_date,
                end_date=end_date,
                reason="测试"
            )

        self.assertIn("开始日期不能晚于结束日期", str(context.exception))

    def test_approve_leave_request_success(self):
        """测试成功批准请假申请"""
        # 先提交请假申请
        start_date = date.today() + timedelta(days=1)
        end_date = date.today() + timedelta(days=2)

        leave_request = LeaveRequest.objects.create(
            employee=self.employee,
            leave_type='sick',
            start_date=start_date,
            end_date=end_date,
            reason="身体不适",
            status='pending'
        )

        # 批准请假
        response = LeaveRequestService.approve_leave_request(
            leave_id=leave_request.leave_id,
            approver_user_id=self.merchant_user.id,
            approval_notes="同意请假，注意身体健康"
        )

        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.data['code'], 200)
        self.assertEqual(response.data['message'], "请假申请批准成功")

        # 验证请假状态
        leave_request.refresh_from_db()
        self.assertEqual(leave_request.status, 'approved')
        self.assertEqual(leave_request.approver, self.approver)
        self.assertIsNotNone(leave_request.approval_time)

    def test_reject_leave_request_success(self):
        """测试成功拒绝请假申请"""
        start_date = date.today() + timedelta(days=1)
        end_date = date.today() + timedelta(days=2)

        leave_request = LeaveRequest.objects.create(
            employee=self.employee,
            leave_type='personal',
            start_date=start_date,
            end_date=end_date,
            reason="私人事务",
            status='pending'
        )

        response = LeaveRequestService.reject_leave_request(
            leave_id=leave_request.leave_id,
            approver_user_id=self.merchant_user.id,
            approval_notes="当前业务繁忙，暂不能批准请假"
        )

        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.data['code'], 200)
        self.assertEqual(response.data['message'], "请假申请已拒绝")

        # 验证请假状态
        leave_request.refresh_from_db()
        self.assertEqual(leave_request.status, 'rejected')


class PerformanceServiceTest(BaseEmployeeTestCase):
    """绩效服务测试"""

    def setUp(self):
        super().setUp()
        # 创建员工
        self.employee = Employee.objects.create(
            user=self.employee_user,
            merchant=self.merchant_info,
            real_name="张三",
            hire_date=date(2024, 1, 15),
            work_start_time=time(9, 0),
            work_end_time=time(18, 0),
            base_daily_salary=Decimal('200.00'),
            late_penalty_per_minute=Decimal('1.0'),
            early_leave_penalty_per_minute=Decimal('1.0'),
            activity_bonus_per_count=Decimal('5.0'),
            monday_work=True,
            tuesday_work=True,
            wednesday_work=True,
            thursday_work=True,
            friday_work=True,
            saturday_work=False,
            sunday_work=False
        )

    def test_calculate_daily_performance_success(self):
        """测试成功计算每日绩效"""
        test_date = date(2024, 7, 1)  # 假设是工作日

        # 创建考勤记录
        Attendance.objects.create(
            employee=self.employee,
            work_date=test_date,
            scheduled_start=time(9, 0),
            scheduled_end=time(18, 0),
            actual_start=time(9, 15),  # 迟到15分钟
            actual_end=time(18, 30)  # 加班30分钟
        )

        # 创建活动记录
        order = Order.objects.create(
            order_id=uuid.uuid4(),
            user=self.employee_user,
            merchant=self.merchant_info,
            table_number="1",
            total_amount=Decimal('50.00')
        )

        order_item = OrderItem.objects.create(
            order=order,
            dish=self.dish,
            quantity=1,
            unit_price=self.dish.price
        )

        EmployeeActivity.objects.create(
            employee=self.employee,
            order_item=order_item,
            activity_type='cook_dish',
            activity_time=datetime.combine(test_date, time(10, 0))
        )

        response = PerformanceService.calculate_daily_performance(
            user_id=self.employee_user.id,
            record_date=test_date
        )

        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.data['code'], 200)
        self.assertEqual(response.data['message'], "绩效计算完成")

        # 验证绩效记录
        performance = PerformanceRecord.objects.get(
            employee=self.employee,
            record_date=test_date
        )

        self.assertTrue(performance.is_present)
        self.assertEqual(performance.late_minutes, 15)
        self.assertEqual(performance.overtime_minutes, 30)
        self.assertEqual(performance.activity_count, 1)

        # 验证工资计算
        expected_base = Decimal('200.00')  # 基础日薪
        expected_late_penalty = Decimal('15.00')  # 15分钟 * 1元/分钟
        expected_activity_bonus = Decimal('5.00')  # 1次活动 * 5元/次
        expected_overtime_bonus = Decimal('12.50')  # 0.5小时 * (200/8)元/小时

        expected_total = expected_base - expected_late_penalty + expected_activity_bonus + expected_overtime_bonus

        self.assertEqual(performance.base_salary, expected_base)
        self.assertEqual(performance.late_penalty, expected_late_penalty)
        self.assertEqual(performance.activity_bonus, expected_activity_bonus)
        self.assertEqual(performance.daily_total_salary, expected_total)

    def test_get_performance_records(self):
        """测试获取绩效记录"""
        test_date = date(2024, 7, 1)

        # 创建绩效记录
        PerformanceRecord.objects.create(
            employee=self.employee,
            record_date=test_date,
            is_work_day=True,
            is_present=True,
            is_on_leave=False,
            late_minutes=15,
            early_leave_minutes=0,
            overtime_minutes=30,
            work_minutes=495,  # 8小时15分钟
            activity_count=2,
            base_salary=Decimal('200.00'),
            late_penalty=Decimal('15.00'),
            early_leave_penalty=Decimal('0.00'),
            activity_bonus=Decimal('10.00'),
            overtime_bonus=Decimal('12.50'),
            daily_total_salary=Decimal('207.50')
        )

        response = PerformanceService.get_performance_records(
            user_id=self.employee_user.id
        )

        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.data['code'], 200)
        self.assertEqual(len(response.data['data']), 1)

        record_data = response.data['data'][0]
        self.assertEqual(record_data['record_date'], test_date.isoformat())
        self.assertEqual(record_data['daily_total_salary'], 207.50)


class SalaryServiceTest(BaseEmployeeTestCase):
    """薪资服务测试"""

    def setUp(self):
        super().setUp()
        # 创建员工
        self.employee = Employee.objects.create(
            user=self.employee_user,
            merchant=self.merchant_info,
            real_name="张三",
            hire_date=date(2024, 1, 15),
            work_start_time=time(9, 0),
            work_end_time=time(18, 0),
            base_daily_salary=Decimal('200.00')
        )

    def test_calculate_salary_success(self):
        """测试成功计算工资"""
        start_date = date(2024, 7, 1)
        end_date = date(2024, 7, 3)

        # 创建3天的绩效记录
        for i in range(3):
            work_date = start_date + timedelta(days=i)
            PerformanceRecord.objects.create(
                employee=self.employee,
                record_date=work_date,
                is_work_day=True,
                is_present=True,
                daily_total_salary=Decimal('200.00')
            )

        response = SalaryService.calculate_salary(
            user_id=self.employee_user.id,
            start_date=start_date,
            end_date=end_date
        )

        self.assertEqual(response.status_code, 201)
        self.assertEqual(response.data['code'], 201)
        self.assertEqual(response.data['message'], "工资计算完成")
        self.assertEqual(response.data['data']['total_salary'], 600.00)
        self.assertEqual(response.data['data']['days_count'], 3)

        # 验证工资记录
        salary_record = SalaryRecord.objects.get(
            employee=self.employee,
            start_date=start_date,
            end_date=end_date
        )
        self.assertEqual(salary_record.total_salary, Decimal('600.00'))

    def test_calculate_salary_no_performance_data(self):
        """测试无绩效数据时计算工资"""
        start_date = date(2024, 7, 1)
        end_date = date(2024, 7, 3)

        with self.assertRaises(ValidationError) as context:
            SalaryService.calculate_salary(
                user_id=self.employee_user.id,
                start_date=start_date,
                end_date=end_date
            )

        self.assertIn("该时间段内无绩效记录", str(context.exception))

    def test_get_salary_records(self):
        """测试获取工资记录"""
        # 创建工资记录
        SalaryRecord.objects.create(
            employee=self.employee,
            start_date=date(2024, 7, 1),
            end_date=date(2024, 7, 31),
            total_salary=Decimal('6000.00')
        )

        response = SalaryService.get_salary_records(
            user_id=self.employee_user.id
        )

        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.data['code'], 200)
        self.assertEqual(len(response.data['data']), 1)

        salary_data = response.data['data'][0]
        self.assertEqual(salary_data['total_salary'], 6000.00)
        self.assertEqual(salary_data['employee_name'], "张三")


class IntegrationTest(BaseEmployeeTestCase):
    """集成测试 - 测试整个工作流程"""

    def test_complete_employee_workflow(self):
        """测试完整的员工工作流程"""
        # 1. 创建员工
        employee_response = EmployeeService.create_employee(
            user_id=self.employee_user.id,
            merchant_id=self.merchant_info.merchant_id,
            real_name="张三",
            hire_date=date(2024, 1, 15),
            work_start_time=time(9, 0),
            work_end_time=time(18, 0),
            base_daily_salary=Decimal('200.00'),
            late_penalty_per_minute=Decimal('1.0'),
            activity_bonus_per_count=Decimal('5.0')
        )
        self.assertEqual(employee_response.status_code, 201)

        # 2. 员工上班打卡
        clock_in_response = AttendanceService.clock_in(
            user_id=self.employee_user.id,
            actual_time=time(9, 15)  # 迟到15分钟
        )
        self.assertEqual(clock_in_response.status_code, 200)

        # 3. 记录工作活动
        order = Order.objects.create(
            order_id=uuid.uuid4(),
            user=self.employee_user,
            merchant=self.merchant_info,
            table_number="1",
            total_amount=Decimal('50.00')
        )

        order_item = OrderItem.objects.create(
            order=order,
            dish=self.dish,
            quantity=1,
            unit_price=self.dish.price
        )

        activity_response = EmployeeActivityService.record_activity(
            user_id=self.employee_user.id,
            order_id=order.order_id,
            dish_id=self.dish.dish_id,
            activity_type='cook_dish'
        )
        self.assertEqual(activity_response.status_code, 201)

        # 4. 员工下班打卡
        clock_out_response = AttendanceService.clock_out(
            user_id=self.employee_user.id,
            actual_time=time(18, 30)  # 加班30分钟
        )
        self.assertEqual(clock_out_response.status_code, 200)

        # 5. 验证自动生成的绩效记录
        today = timezone.now().date()
        performance_record = PerformanceRecord.objects.get(
            employee__user_id=self.employee_user.id,
            record_date=today
        )

        self.assertEqual(performance_record.late_minutes, 15)
        self.assertEqual(performance_record.overtime_minutes, 30)
        self.assertEqual(performance_record.activity_count, 1)

        # 验证工资计算
        expected_total = (
                Decimal('200.00') -  # 基础工资
                Decimal('15.00') +  # 迟到扣款
                Decimal('5.00') +  # 活动奖金
                Decimal('12.50')  # 加班费 (0.5小时 * 25元/小时)
        )
        self.assertEqual(performance_record.daily_total_salary, expected_total)

        print(f"集成测试完成！员工今日总工资：{performance_record.daily_total_salary}元")


# 运行测试的命令行脚本
if __name__ == '__main__':
    import django
    import os
    import sys

    # 设置Django环境
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'TasteLink0.settings')
    django.setup()

    # 运行测试
    from django.test.utils import get_runner
    from django.conf import settings

    TestRunner = get_runner(settings)
    test_runner = TestRunner(verbosity=2, interactive=True)
    failures = test_runner.run_tests(['__main__'])

    if failures:
        sys.exit(1)